package com.cus.tom.transfer.frag;

import android.animation.ValueAnimator;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Environment;
import android.util.SparseIntArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.cus.tom.transfer.App;
import com.cus.tom.transfer.ac.CodeAct;
import com.cus.tom.transfer.adapter.FileAdapter;
import com.cus.tom.transfer.bean.Const;
import com.cus.tom.transfer.bean.FileType;
import com.cus.tom.transfer.databinding.FragFileBinding;
import com.cus.tom.transfer.utils.ComUtility;
import com.cus.tom.transfer.utils.Read;
import com.cus.tom.transfer.utils.ToastUtil;
import com.cus.tom.transfer.utils.Utils;
import com.cus.tom.transfer.view.CustomTabProvider;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.plata.base.aclr.common.SilentTask;
import com.plata.base.aclr.common.TaskEngine;

import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;

public class FileFragment extends ChangeFragment {

    FragFileBinding binding;
    BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            ImgFragment.img.clear();
            ImgFragment.audio.clear();
            ImgFragment.video.clear();
            AppFragment.set.clear();

            binding.pager.setAdapter(new FileAdapter(getChildFragmentManager(), 2));
            binding.tab.setViewPager(binding.pager);
        }
    };

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        getActivity().unregisterReceiver(receiver);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = FragFileBinding.inflate(inflater, container, false);

        IntentFilter filter = new IntentFilter(Const.EXIT_RESULT);
        getActivity().registerReceiver(receiver, filter);

        binding.tab.setCustomTabView(new CustomTabProvider(getActivity()));
        binding.pager.setAdapter(new FileAdapter(getChildFragmentManager(), 2));
        binding.tab.setViewPager(binding.pager);

        binding.get.setOnClickListener(v -> {
            Read.toRead(getActivity(), "需要读取存储文件权限以便存储接收的文件", new Runnable() {
                @Override
                public void run() {
                    if (XXPermissions.isGranted(getActivity(), Permission.MANAGE_EXTERNAL_STORAGE)) {
                        Read.toSetting(getActivity(), runnable, false, Permission.CAMERA);
                    }
                }
            });
        });
        binding.send.setOnClickListener(v -> {
            int count = 0;
            for (int i = 0; i < array.size(); i++) {
                count += array.valueAt(i);
            }
            if (count == 0) {
                ToastUtil.showShortToast(getActivity(), "请选择要发送的文件");
                return;
            }
            prepare();
        });

        return binding.getRoot();
    }

    SparseIntArray array = new SparseIntArray();

    public void updateBtn(int num, int index) {
        array.put(index, num);
        int count = 0;
        for (int i = 0; i < array.size(); i++) {
            count += array.valueAt(i);
        }
        int end;
        if (count == 0) {
            binding.send.setText("发");
            end = Utils.dp2Px(getActivity(), 50);
        } else {
            binding.send.setText(String.format("发送（%d）", count));
            end = Utils.getScreenWidth() - Utils.dp2Px(getActivity(), 20);
        }
        changeSize(end);
    }

    private void changeSize(int end) {
        int start = binding.send.getWidth();
        if (start == end) {
            return;
        }
        ValueAnimator anim = ValueAnimator.ofInt(start, end);
        anim.setDuration(300);
        anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(@NonNull ValueAnimator animation) {
                int i = (Integer) animation.getAnimatedValue();
                binding.send.getLayoutParams().width = i;
                binding.send.requestLayout();
            }
        });
        anim.start();
    }

    private void prepare() {
        LoadingDlg dlg = new LoadingDlg();
        dlg.show(getChildFragmentManager(), "");
        TaskEngine.getInstance().submit(new SilentTask("") {
            @Override
            public void runInBackground() throws Exception {
                ArrayList<String> list = doPrepare();
                h.post(() -> {
                    dlg.dismiss();
                    HashSet<Integer> select = new HashSet<>();
                    FileType[] values = FileType.values();
                    for (FileType t : values) {
                        if (array.get(t.getCode(), 0) > 0) {
                            select.add(t.getCode());
                        }
                    }
                    Intent i = new Intent(getActivity(), CodeAct.class);
                    i.putStringArrayListExtra("files", list);
                    i.putExtra("set", select);
                    startActivity(i);
                });
            }

            @Override
            public long getTimeout() {
                return 0;
            }
        });
    }

    private ArrayList<String> doPrepare() {
        try {
            File f = new File(Environment.getExternalStorageDirectory(), App.getApp().getPackageName());
            if (f.exists()) {
                Utils.deleteFile(f);
            }
            if (array.get(FileType.APP.getCode(), 0) > 0) {
                return copyApp(AppFragment.set);
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return new ArrayList();
    }

    private ArrayList<String> copyApp(Set<String> set) {
        File f = new File(Environment.getExternalStorageDirectory(), App.getApp().getPackageName());
        f.mkdirs();
        ArrayList<String> list = new ArrayList<>();
        for (String name : set) {
            String str = ComUtility.android_command("pm path " + name);
            str = str.substring(str.indexOf("/"));
            StringBuffer sb = new StringBuffer();
            File tmp = new File(f, name + ".apk");
            sb.append("cp ").append(str).append(" ").append(tmp.getAbsolutePath());
            str = ComUtility.android_command(sb.toString());
            list.add(tmp.getAbsolutePath());
            System.currentTimeMillis();
        }
        return list;
    }
}
